﻿using Microsoft.AspNetCore.Mvc;
using bpms.Dao;
using bpms.Models;
using bpms.Service;
using bpms.Utils;

namespace bpms.Controllers
{
    /// <summary>
    /// 饮品模块
    /// </summary>
    public class ProductController : BaseController
    {
        private readonly ProductService _productService;
        private readonly OrderService _orderService;
        private readonly IWebHostEnvironment _env;
        public ProductController(ProductService proService, OrderService orderService,IWebHostEnvironment env)
        {
            _productService = proService;
            _orderService = orderService;
            _env = env;
        }
        public IActionResult Index(string searchKey)
        {
            var products = _productService.GetList(searchKey);
            return View("Index", products);
        }

        // 详情页
        public IActionResult Detail(int id)
        {
            var product = _productService.GetById(id);
            return View(product);
        }

        // 新增页
        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Add(Product product, IFormFile imageFile)
        {
            if (ModelState.IsValid)
            {
                // 处理图片上传
                if (imageFile != null && imageFile.Length > 0)
                {
                    product.Image = await SaveImage(imageFile);
                }
                product.Status = 0;//默认未上架
                product.CreatedUser = CurrentUser.Id;
                _productService.Add(product);
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

        // 编辑页
        public IActionResult Edit(int id)
        {
            var product = _productService.GetById(id);
            return View(product);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, Product product, IFormFile imageFile)
        {
            if (id != product.Id) return NotFound();
            ModelState.Remove("imageFile");
            if (ModelState.IsValid)
            {
                // 获取原有产品信息
                var existingProduct = _productService.GetById(id);
                product.Image = existingProduct.Image;
                //如果重新上传了图片，则替换之前的图片路径
                if (imageFile != null && imageFile.Length > 0)
                {
                    product.Image = await SaveImage(imageFile);
                }
                _productService.Update(product);
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

       
        // 删除操作
        public IActionResult Delete(int id)
        {
           _productService.Delete(id);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 上下架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult UpOrDown(int id,int status)
        {
            var convertStatus = status == 1 ? 0 : 1;
            var product = _productService.UpOrDown(id, convertStatus);
            return RedirectToAction("Index");
        }





        /// <summary>
        /// 跳转到购买页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Buy(int? id)
        {
            if (id == null) return NotFound();

            var product = _productService.GetById(id.Value);
            if (product == null) return NotFound();

            var viewModel = new BuyViewModel
            {
                ProductId = product.Id,
                ProductNo = product.ProductNo,
                ProductName = product.Name,
                Price = product.Price,
                Stock = product.Stock,
                Quantity = 1,
                DeliveryTime = DateTime.Now.AddDays(1)//默认明天配送
            };

            return View(viewModel);
        }

        /// <summary>
        /// 购买保存生成订单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Buy(BuyViewModel model)
        {
            if (!ModelState.IsValid) return View(model);

            var product = _productService.GetById(model.ProductId);
            if (product == null)
            {
                ModelState.AddModelError(string.Empty, "商品不存在");
                return View(model);
            }

            if (product.Stock < model.Quantity)
            {
                ModelState.AddModelError("Quantity", "库存不足");
                return View(model);
            }

            // 生成订单号
            string orderNo = $"{DateTime.Now:yyyyMMddHHmmssfff}";

            var order = new Order
            {
                OrderNo = orderNo,
                ProductID = model.ProductId,
                Quantity = model.Quantity,
                TotalAmount = product.Price * model.Quantity, // 使用数据库中的价格
                DeliveryTime = model.DeliveryTime,
                CustomerID = CurrentUser.Id, // 实现获取当前用户ID
            };
            _orderService.Add(order);
            return RedirectToAction("Index", "Order");
        }

        #region 私有方法
        private async Task<string> SaveImage(IFormFile imageFile)
        {
            var uploadsDir = Path.Combine(_env.WebRootPath, "uploads/images");
            Directory.CreateDirectory(uploadsDir);

            var fileName = $"{Guid.NewGuid()}{Path.GetExtension(imageFile.FileName)}";
            var filePath = Path.Combine(uploadsDir, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await imageFile.CopyToAsync(stream);
            }

            return $"/uploads/images/{fileName}";
        }

        private void DeleteImage(string imagePath)
        {
            if (!string.IsNullOrEmpty(imagePath))
            {
                var fullPath = Path.Combine(_env.WebRootPath, imagePath.TrimStart('/'));
                if (System.IO.File.Exists(fullPath))
                {
                    System.IO.File.Delete(fullPath);
                }
            }
        }
        #endregion
    }
}
